<script setup>
import {reactive, ref, watch} from "vue";
import {User, Lock} from '@element-plus/icons-vue'
import {login} from "../api/login.js";
import {ElMessage} from "element-plus";
import {config} from "../config/index.js";
import {useRouter} from "vue-router";

const router = useRouter()

const loginInfo = reactive({
  username: "",
  password: "",
})

//定义表单引用，名字和ref指定的必须相同
const loginRef = ref()
const loginBtnDisabled = ref(true)

//校验
const rules = reactive({
  username: [
    {required: true, message: '请输入用户名', trigger: 'blur'},
  ],
  password: [
    {required: true, message: '请输入密码', trigger: 'blur'},
  ],
})

//监听登录表单数据
watch(loginInfo, () => {
  loginRef.value.validate((valid) => {
    //为登录按按钮禁用赋值
    loginBtnDisabled.value = !valid;
  })
})

//登录方法
const loginSubmit = () => {
  login(loginInfo).then(response => {
    if (response.data.code === 200) {
      ElMessage({
        message: response.data.message,
        type: 'success',
      })
      localStorage.setItem(config.tokenName, response.data.data)
      router.replace('/')
    } else {
      ElMessage.error(response.data.message)
    }
  })
}
</script>

<template>
  <el-card class="box-card">
    <h2>登录管理后台</h2>
    <el-form
        ref="loginRef"
        :model="loginInfo"
        :rules="rules"
    >
      <el-form-item label="" prop="username" class="form-item">
        <el-input v-model="loginInfo.username" :prefix-icon="User" placeholder="请输入用户名" :clearable="true"/>
      </el-form-item>
      <el-form-item label="" prop="password" class="form-item">
        <el-input v-model="loginInfo.password" type="password" autocomplete="off" :prefix-icon="Lock"
                  placeholder="请输入密码" show-password/>
      </el-form-item>
      <el-form-item class="center-btn">
        <el-button :disabled="loginBtnDisabled" type="primary" @click="loginSubmit()">
          登录
        </el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<style lang="less" scoped>
.box-card {
  width: 480px;
  margin: 0 auto;

  .form-item {
    width: 240px;
    margin: 0 auto 20px;
  }

  .center-btn {
    justify-content: center;
    margin: 0 auto;
    width: 80px
  }
}
</style>